<?php
declare (strict_types = 1);

namespace app\index\controller;


use app\index\BaseController;
use app\index\logic\Token;
use app\index\model\Category;
use app\index\model\Limit;
use app\index\model\Product;
use scws\PSCWS4;
use think\cache\driver\Redis;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Filesystem;
use think\facade\Log;
use think\facade\Request;
use think\facade\Session;
use think\facade\View;

class Index extends BaseController
{
    private $echostr;
    private $arr;
    //首页
    public function index()
    {
        if (isset($_GET['code']) && !empty($_GET['code'])){
            Token::token($_GET['code']);
        }
        $this->redis->auth('123456');
        $headImg = Db::name('user')->where('id','=',Session::get('user'))->find();
        View::assign('headImg',$headImg);
        if (!$this->redis->get("index_hot")){
//            echo 1;
            $hot = Product::where('is_hot','=',1)->limit(6)->select();
            //序列化变成字符串
            $this->redis->set("index_hot",serialize($hot),1000);
        }
        if (!$this->redis->get("index_show")){
//            echo 2;
            $show = Product::where('is_show','=',1)->limit(6)->select();
            //序列化变成字符串
            $this->redis->set("index_show",serialize($show),1100);
        }
        //秒杀商品
        $limit = Limit::select();
        View::assign('time',time());
        View::assign('limit',$limit);
        View::assign('hot',unserialize($this->redis->get("index_hot")));
        View::assign('show',unserialize($this->redis->get("index_show")));
        $cate = Category::where('parentid','=','0')->order('sort')->limit(3)->select();
        View::assign('cate',$cate->toArray());

        return View::fetch();
    }
    //分词搜索
    public function key()
    {
        $post = Request::post();
        $text = $this->request->param($post);
        $pscws = new PSCWS4();
        $pscws ->set_charset('utf8');
        $pscws->set_dict(ROOT_PATH.'/extend/scws/etc/dict.utf8.xdb');
        $pscws->set_rule(ROOT_PATH.'/extend/scws/etc/rules.ini');
        $pscws->send_text($text);
        $tops = $pscws->get_tops(10,'n,v');
    }

    //公众号
    public function link()
    {
        $rt = $this->check($this->request);
        if ($rt){
            if (!empty($this->echostr)){
                ob_clean();//清除缓存
                echo $this->echostr;//返回给微信的字符串
            }else{
                $xml = file_get_contents("php://input");//接受xml包
                Log::record($xml);
                $this->arr = $this->xml2array($xml);
            }

        }
    }
    public function check($request)
    {
        $signature = $request->param("signature");
        $timestamp = $request->param("timestamp");
        $nonce = $request->param("nonce");
        $this->echostr = $request->param("echostr");
        $token = "fuziyue";
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
//        Log::record($signature."|".$timestamp."|".$nonce);
//        Log::record($signature."|".$tmpStr);
        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }
    //将微信的xml转换为数组
    protected function xml2array($xml)
    {
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $result = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $result;
    }

    //微信小程序接口
    public function wxApi()
    {
        $list = Product::where('is_show','=',1)->limit(6)->select();
        //将数据库中查询得数据转换成json返回给小程序
        return json($list);
    }
    public function wxApi2()
    {
        $id = Request::post('id');
        $info = Product::where('id','=',$id)->find();
        return json($info);
    }
    //小程序上传图片
    public function upload()
    {
        $file = Request::file("file");
        $savename = Filesystem::disk('public')->putFile("UploadFiles",$file);
        echo "https://shop.fzyhh.top/storage/".$savename;
        exit;
    }
    //小程序登录
    public function login()
    {
        $code = Request::post('code');//小程序端发来的code
        // curl方式拿着code换openid
        $appid="wx3e2cb31b15cb13d7";
        $secret="bc0a5e23b1bbb6e6098cbe25a05d7dcf";
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code";
        $rt = https_request($url);
        $open_key=json_decode($rt,true);
        //查询是否为老用户
        $info=Db::table("lr_user")
            ->where("openid",$open_key['openid'])
            ->find();
        if (!$info){//新用户 执行添加操作
            $id = Db::table("lr_user")->insertGetId(['openid'=>$open_key['openid'],'addtime'=>time()]);
            //将添加的主键 添值info数组中
            $info=[
              'id'=>$id,
              'openid'=>$open_key['openid']
            ];
        }
        //生成登录态 存储info数组
        //uniqid() 根据毫秒级时间戳 生成唯一编码
        //uniqid()+openid 在sha1加密 生成登录态
        $key = sha1(uniqid().$open_key['openid']);
        Cache::set($key,$info);
        echo $key;
        exit;
    }
    public function getUser()
    {
        $sid = Request::post('sid');//登录态
        $arr = Cache::get($sid);//根据登录态获取openid和主键
        $info = Db::table("lr_user")
            ->where("openid",$arr['openid'])
            ->find();
        return json($info);
    }
    public function updateUser()
    {
        $sid = Request::post('sid');//登录态
        $arr = Cache::get($sid);
        $name = Request::post('name');
        $img = Request::post('headimg');
        $sex = Request::post('sex');
        $edid = Db::table("lr_user")
            ->where('openid',$arr['openid'])
            ->update(['nickname'=>$name,'head_img'=>$img,'sex'=>$sex]);
        return $edid;
    }
    public function wxbanner()
    {
        $banner = Db::table('lr_banner')->select()->toArray();
        return $banner;
    }
    //photoBook项目接口
    //查询班级
    public function wxclass()
    {
        $class = Db::table('lr_class')->select()->toArray();
        foreach ($class as &$v){
            $count = Db::table('lr_telbook')->where('class_id','=',$v['id'])->count();
            $v['count']=$count;
        }

        if ($class!=null){
            return json($class);
        }else{
            return [];
        }
    }
    //商城登录
    public function shopLogin()
    {
        $code = Request::post('code');//小程序端发来的code
        // curl方式拿着code换openid
        $appid="wx3e2cb31b15cb13d7";
        $secret="bc0a5e23b1bbb6e6098cbe25a05d7dcf";
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code";
        $rt = https_request($url);
        $open_key=json_decode($rt,true);
        //查询是否为老用户
        $info=Db::table("lr_telbook")
            ->where("openid",'=',$open_key['openid'])
            ->find();
        if (!$info){//新用户 执行添加操作
            $id = Db::table("lr_telbook")->insertGetId(['openid'=>$open_key['openid'],'addtime'=>time()]);
            //将添加的主键 添值info数组中
            $info=[
                'id'=>$id,
                'openid'=>$open_key['openid']
            ];
        }
        //生成登录态 存储info数组
        //uniqid() 根据毫秒级时间戳 生成唯一编码
        //uniqid()+openid 在sha1加密 生成登录态
        $key = sha1(uniqid().$open_key['openid']);
        Cache::set($key,$info);
        return $key;
    }
    //更新用户信息
    public function wxUser()
    {
        $sid = Request::post('sid');//登录态
        $arr = Cache::get($sid);
        $name = Request::post('name');
        $img = Request::post('headimg');
        $sex = Request::post('sex');
        $edid = Db::table("lr_telbook")
            ->where('openid','=',$arr['openid'])
            ->update(['nickname'=>$name,'headimg'=>$img,'sex'=>$sex,'addtime'=>time(),'name'=>$name,'tel'=>'','class_id'=>1,'semester_id'=>1]);
        $find = Db::table("lr_telbook")
            ->alias('t')
            ->field('t.*,lc.class_name,ls.semester')
            ->where("t.openid",'=',$arr['openid'])
            ->join('lr_class lc','lc.id=t.class_id')
            ->join('lr_semester ls','ls.id=t.semester_id')
            ->find();
        if ($find['sex']==1){
            $find['sex']='男';
        }else{
            $find['sex']='女';
        }
        return json($find);
    }
    //获取用户信息
    public function wxGetUser()
    {
        $sid = Request::post('sid');//登录态
        $arr = Cache::get($sid);//根据登录态获取openid和主键
        $info = Db::table("lr_telbook")
            ->where("openid",$arr['openid'])
            ->find();
        return json($info);
    }
    //user获取信息
    public function wxGetUsers()
    {
        $sid = Request::post('sid');//登录态
        $arr = Cache::get($sid);//根据登录态获取openid和主键
        $find = Db::table("lr_telbook")
            ->alias('t')
            ->field('t.*,lc.class_name,ls.semester')
            ->where("t.openid",'=',$arr['openid'])
            ->join('lr_class lc','lc.id=t.class_id')
            ->join('lr_semester ls','ls.id=t.semester_id')
            ->find();
        if ($find != null){
            if ($find['sex']==1){
                $find['sex']='男';
            }else{
                $find['sex']='女';
            }
            return json($find);
        }
    }
    //获取班级
    public function wxGetClass()
    {
        $class = Db::table('lr_class')
            ->select();
        return json($class);
    }
    //获取学期
    public function wxGetSemester()
    {
        $semester = Db::table('lr_semester')
            ->select();
        return json($semester);
    }
    //图片修改
    public function getUpload()
    {
        $file = Request::file("file");
        $savename = Filesystem::disk('public')->putFile("UploadFiles",$file);
        return "https://shop.fzyhh.top/storage/".$savename;
    }

    //添加用户信息
    public function addGetUser()
    {
        $sid = Request::post('sid');//登录态
        $arr = Cache::get($sid);//根据登录态获取openid和主键
        $post = Request::post();
        $class = $post['class']+1;
        $semester = $post['semester']+1;
        try{
            $edit = Db::table('lr_telbook')
                ->where('openid','=',$arr['openid'])
                ->update(['tel'=>$post['tel'],'sex'=>$post['sex'],'class_id'=>$class,'semester_id'=>$semester,'name'=>$post['name'],'headimg'=>$post['src']]);
        }catch (\Exception $e){
            echo $e->getMessage();
            $edit = false;
        }
    }
    //展示学生信息
    public function getUsers()
    {
        $post = Request::post();
        $list = Db::table('lr_telbook')
            ->where('class_id','=',$post['id'])
            ->select();
        return json($list);
    }
    //展示学生信息
    public function getsemUsers()
    {
        $post = Request::post();
        $list = Db::table('lr_telbook')
            ->where('semester_id','=',$post['id'])
            ->select();
        return json($list);
    }
    //获取学习
    public function getSubject()
    {
        $list = Db::table('lr_semester')->select()->toArray();
        foreach ($list as &$v){
            $v['count'] = Db::table('lr_telbook')->where('semester_id','=',$v['id'])->count();
        }
        if ($list!=null){
            return json($list);
        }else{
            return [];
        }
    }
    public function keyGet()
    {
        $post = Request::post();
        $key = Db::table('lr_telbook')
            ->where('name','like','%'.$post['key'].'%')
            ->select();
        return $key;
    }
    //wx_shopping_mall项目
    //轮播图
    public function shopBanner()
    {
        $banner = Db::table('lr_banner')->order('sort','desc')->select()->toArray();
        foreach ($banner as &$v){
            $v['photo'] = "https://shop.fzyhh.top/static/".$v['photo'];
        }
        return json($banner);
    }
    //首页展示商品
    public function shopIndexShow()
    {
        $indexShow = Db::table('lr_product')
            ->where('is_show','=','1')
            ->select()->toArray();
//        foreach ($indexShow as &$v){
//            $v['photo_x'] = "https://shop.fzyhh.top/static/".$v['photo_x'];
//            if (mb_strlen($v['content'])>){
//                return mb_substr($d['goods_name'],0,6,'utf-8').'...';
//            }else{
//                return $d['goods_name'];
//            }
//        }
        return json($indexShow);
    }





















}
